package com.remote;

import android.os.Bundle;
import android.os.Message;
import android.os.Handler;
import android.os.RemoteException;
import android.widget.*;
import android.widget.LinearLayout.LayoutParams;
import android.view.Gravity;
import android.view.View.OnClickListener;
import android.view.View;
import android.view.ViewGroup;
import android.content.Intent;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Typeface;
import android.app.Dialog;
import java.util.ArrayList;
import java.util.Iterator;
import android.util.Log;

public class RemoteCommandActivity extends Remote{
    private RelativeLayout mLayout;
    private ArrayList<Server> Servers;

    private Dialog dialog;
    private EditText portText;
    private int id=100;
    
    @Override
    protected void parseMessage(Message msg){
        Bundle bData;
        Log.i(TAG,"Received msg");
        switch(msg.what){
            case Params.MSG_INITIALIZED:
                Log.i(TAG,"Connection initialized");
                startActivity(new Intent(RemoteCommandActivity.this,AppPicker.class));
                break;
            case Params.MSG_SERVER_RESPONSE:
                Log.i(TAG,"Received search response from server");
                bData = msg.peekData();
                if(bData == null) break;        // ignore server with no data
                if(checkServerExists(bData)) break;     // ignore already displayed server
                
                Server server = new Server(RemoteCommandActivity.this,bData,id++);
                Servers.add(server);
                mLayout.addView(server.getLayout());
                
                break;
            default:
                Log.d(TAG,"Parsing unknown message");
                break;
        }
    }
    
    private void sendSearchParty(int port){
        if(Pipe != null){
            sendMsg(Params.MSG_SEARCH_SERVER,port);
        }
    }
    
    private void sendStartListening(int port){
        if(Pipe != null){
            sendMsg(Params.MSG_START_LISTENING,port);
        }
    }
    
    private void openSearchPortDialog(){
        dialog = new Dialog(RemoteCommandActivity.this);
        
        dialog.setContentView(R.layout.select_search_port);
        dialog.setTitle("Select Search port");
        
        portText = (EditText)dialog.findViewById(R.id.editPort);
        Button bSearch = (Button)dialog.findViewById(R.id.search_button);
        
        bSearch.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                sendSearchParty(Integer.parseInt(portText.getText().toString()));
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    
    private void openListenPortDialog(){
        dialog = new Dialog(RemoteCommandActivity.this);
        
        dialog.setContentView(R.layout.select_listen_port);
        dialog.setTitle("Select Listening port");
        
        portText = (EditText)dialog.findViewById(R.id.editPort);
        Button bSearch = (Button)dialog.findViewById(R.id.listen_button);
        
        if(bSearch != null) bSearch.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                sendStartListening(Integer.parseInt(portText.getText().toString()));
                dialog.dismiss();
            }
        });
        dialog.show();
    }
    
    public void HackServer(Context context,int id){
        Server server = new Server(context,Utils.getServerBundle(new String[] {"susA","192.168.1.2","3333","SuseOpen"}),id);
        Servers.add(server);
        mLayout.addView(server.getLayout());
    }
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.server_search);
        mLayout = (RelativeLayout)findViewById(R.id.rLayout);
        
        Servers = new ArrayList<Server>();

        ImageButton search = (ImageButton)findViewById(R.id.search_server);
        
        try{Thread.sleep(500);}catch(InterruptedException e){}
        openListenPortDialog();
        HackServer(RemoteCommandActivity.this,id++);

        search.setOnClickListener(new OnClickListener(){
            @Override
            public void onClick(View v){
                Log.i(TAG,"search button pressed");
                openSearchPortDialog();
            }
        });
    }
    
    @Override
    public void onStart(){
        super.onStart();
    }
    
    private class Server{
        private LinearLayout sLayout;
        private Bundle sInfo;
        private int id;
        
        public Server(Context context,Bundle sInfo,int id){
            this.sInfo = sInfo;
            this.id = id;
            this.sLayout = getServerInfoLayout(context,sInfo,id);
            
            RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT);
            
            if(Servers.isEmpty()) params.addRule(RelativeLayout.BELOW, R.id.headerLayout);
            else params.addRule(RelativeLayout.BELOW,Servers.get(Servers.size()-1).getId());
            sLayout.setLayoutParams(params);
        }
        
        public int getId(){return id;}
        public Bundle getInfo(){return sInfo;}
        public LinearLayout getLayout(){return sLayout;}
    }
    
    //! returns true if server is already displayed
    public boolean checkServerExists(Bundle sInfo){
        Iterator<Server> it = Servers.iterator();
        Bundle tmpInfo;
        
        while(it.hasNext()){
            tmpInfo = it.next().getInfo();
            if(tmpInfo.getString("name").compareTo(sInfo.getString("name"))==0) return true;        // if same names return true
        }
        return false;
    }
    
    private LinearLayout getServerInfoLayout(Context context,Bundle serverInfo,int id){
        LinearLayout sLayout = new LinearLayout(RemoteCommandActivity.this);
        sLayout.setId(id);
    
        sLayout.setOrientation(LinearLayout.HORIZONTAL);
        
        LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);

        //! server logo
        ImageView sLogo = new ImageView(context);
        sLogo.setImageDrawable(context.getResources().getDrawable(R.drawable.opensuse));
        sLayout.addView(sLogo,params);
        
        //! server info layout
        params = new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT);
        LinearLayout sInfoLayout = new LinearLayout(context);
        sInfoLayout.setGravity(Gravity.BOTTOM);
        sInfoLayout.setOrientation(LinearLayout.VERTICAL);
        
        TextView sNameInfo = new TextView(context);
        sNameInfo.setTextSize(16);
        sNameInfo.setTypeface(Typeface.DEFAULT,Typeface.BOLD);
        sNameInfo.setText(serverInfo.getString("name")+" - "+serverInfo.getString("info"));
        sInfoLayout.addView(sNameInfo);
        
        TextView sAddressPort = new TextView(context);
        sAddressPort.setTextSize(16);
        sAddressPort.setText(serverInfo.getString("address")+" : "+String.valueOf(serverInfo.getInt("port")));
        sInfoLayout.addView(sAddressPort);
        
        sLayout.setClickable(true);
        sLayout.setOnClickListener(serverClickListener);
        sLayout.addView(sInfoLayout,params);
        
        return sLayout;
    }
    
    private OnClickListener serverClickListener = new OnClickListener(){
        public void onClick(View v){
            Log.v("Click","Clicked layout with id: "+v.getId());
            v.setBackgroundResource(android.R.drawable.list_selector_background);      // list_selector_background
            
            if(Pipe != null){
                sendMsg(Params.MSG_INITIALIZE,Servers.get(v.getId()-100).getInfo());
            }
        }
    };
}
